package au.edu.utas.yu_qiao_group.luckyman.ui.recordlist;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import au.edu.utas.yu_qiao_group.luckyman.MainActivity;
import au.edu.utas.yu_qiao_group.luckyman.db.raffles.RaffleDTO;

public class RaffleListAdapter extends ArrayAdapter<RaffleDTO> {
  Context mContext;
  ArrayList<RaffleDTO> mData = null;
  List<RaffleDTO> mFilteredData = null;

  public RaffleListAdapter(Context mContext, ArrayList<RaffleDTO> data) {

    super(mContext, android.R.layout.simple_list_item_activated_1, data);

    this.mContext = mContext;
    this.mData = data;
    this.mFilteredData = data;
  }

  @Override
  public int getCount()
  {
    return mFilteredData.size();
  }

  @Override
  public RaffleDTO getItem(int position)
  {
    return mFilteredData.get(position);
  }

  @Override
  public long getItemId(int position)
  {
    return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

    try {
      if (convertView == null) {
        LayoutInflater inflater = ((MainActivity) mContext).getLayoutInflater();
        convertView = inflater.inflate(android.R.layout.simple_list_item_activated_1, parent, false);
      }

      RaffleDTO r = mFilteredData.get(position);

      TextView textViewItem = (TextView) convertView.findViewById(android.R.id.text1);
      textViewItem.setText(r.getMName());

    } catch (NullPointerException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return convertView;

  }

  @Override
  public Filter getFilter() {
    return new Filter() {
      @Override
      protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        if (constraint == null || constraint.length() == 0) {
          results.values = mData;
          results.count = mData.size();
        } else {
          List<RaffleDTO> filterResultsData = mData.stream()
                  .filter(i -> i.getMName().toLowerCase().contains(constraint.toString().toLowerCase()))
                  .collect(Collectors.toList());
          results.values = filterResultsData;
          results.count = filterResultsData.size();
        }

        return results;
      }

      @Override
      protected void publishResults(CharSequence constraint, FilterResults results) {
        mFilteredData = (List<RaffleDTO>) results.values;
        notifyDataSetChanged();
      }
    };
  }
}
